# -*- coding:utf8 -*-
"""
使用bosonnlp获取相应的服务
"""
from __future__ import print_function
from bosonnlp import BosonNLP
import requests
from json import dumps

HTTPError = requests.exceptions.HTTPError


def retry(fun):
    def wrap(*args, **kwargs):
        try:
            ret = fun(*args, **kwargs)
            return ret

        except HTTPError as e:
            raise


class BosonWrapper(object):

    users = {
        "183569445@qq.com": "LUb9m5wx.8242.S7q8mWPy2Kcy",
        "435529698@qq.com": "wRZ5MKfZ.10220.lcxAy7D6X4eJ",
        "364879438@qq.com": "IN5eNG2g.10224.CyoP9JamWaSD",
        "dl2004855@163.com": "YD3P4hvz.10241.4GVMIbWxocqi"
    }
    users_ = {
        ("435529698", "435529698@qq.com", "123456"),
        ("364879438", "364879438@qq.com", "1234567890"),
        ("dl2004855", "dl2004855@163.com", "123456")
    }

    def __init__(self, space_mode=0, oov_level=4, t2s=0, special_char_conv=0):
        """
        配置boson的一些参数，与其默认参数是有区别的
        :param space_mode:
        :param oov_level:
        :param t2s:
        :param special_char_conv:
        """
        self.api_tokens = list(self.users.values())
        self.nlp = BosonNLP(self.api_tokens[0])
        self.space_mode = space_mode
        self.oov_level = oov_level
        self.t2s = t2s
        self.special_char_conv = special_char_conv

    def segment(self, content):
        words, tags = self.postag_unicode(content)
        return words

    def segment_unicode(self, content):
        words, tags = self.postag_unicode(content)
        return words

    def postag(self, contents):
        return self.postag_unicode(contents)

    def postag_unicode(self, content):
        """
        进行实际的操作
        :param content: 正文，utf8编码或者unicode都没有关系
        :return: words, tags
        """
        result = self.nlp.tag(content,
                              space_mode=self.space_mode,
                              oov_level=self.oov_level,
                              t2s=self.t2s,
                              special_char_conv=self.special_char_conv)
        return result

    def sentiment(self, contents, model=None):
        """
        情感分析
        :return:
        """
        result = self.nlp.sentiment(contents, model)
        return result

    def ner(self, contents):  # sensitivity=None, segmented=False):
        return self.nlp.ner(contents)

    # space_mode=0, oov_level=3, t2s=0, special_char_conv=0):
    def tag(self, contents):
        return self.nlp.tag(contents)

    @staticmethod
    def limit_exceed(e):
        return e.response.status_code == 429


if __name__ == '__main__':
    import json
    boson = BosonWrapper()
    contents = ['你是个贱人', '你到底有没有病', '去你妈的毛病']
    print(json.dumps(
        boson.postag(contents), ensure_ascii=False, indent=2
    ))
    print(json.dumps(
        boson.sentiment(contents, model='food'), ensure_ascii=False, indent=2
    ))